package controllers;

import java.util.Calendar;
import java.util.List;

import models.Notification;
import models.User;
import play.mvc.*;

@With(Secure.class)
public class Notifications extends Controller {

	/**
	 * This method is called to generate instant notifications to the user. It
	 * checks the notifications not read by the user, and checks if those should
	 * be made as a pop-out or not.
	 * 
	 * @param userId
	 *            The id of the user to be checked for notifications
	 */
	public static void getNotification(long userId) {
		User temp = User.findById(userId);
		if (!temp.isNotified) {
			return;
		} else {
			Calendar now = Calendar.getInstance();
			List<Notification> allNotification = Notification.find("userId",
					userId).fetch();
			/**
			 * Checks for already read notifications and removes them.
			 */
			for (int i = 0; i < allNotification.size(); i++) {
				if (allNotification.get(i).status == true) {
					allNotification.remove(i).save();
					i--;
				}
			}

			/**
			 * Checks if the remaining unread messages were done more than 5
			 * mins ago, if yes, it removes that.
			 */
			for (int i = 0; i < allNotification.size(); i++) {
				if (allNotification.get(i).date.get(Calendar.MONTH) == now
						.get(Calendar.MONTH)
						&& allNotification.get(i).date.get(Calendar.YEAR) == now
								.get(Calendar.YEAR)
						&& allNotification.get(i).date
								.get(Calendar.DAY_OF_MONTH) == now
								.get(Calendar.DAY_OF_MONTH)
						&& allNotification.get(i).date.get(Calendar.HOUR) == now
								.get(Calendar.HOUR)
						&& now.get(Calendar.MINUTE)
								- allNotification.get(i).date
										.get(Calendar.MINUTE) > 5) {
					allNotification.remove(i).save();
					i--;
				}
			}
			/**
			 * Returns one of the notifications pending, and sets it to read.
			 */
			if (!allNotification.isEmpty()) {
				Notification notify = allNotification.get(0);
				notify.status = true;
				notify.save();
				int ago = now.get(Calendar.MINUTE)
						- notify.date.get(Calendar.MINUTE);
				notify.main = notify.main + " " + ago + "m ago";
				// notify.save();

				renderJSON(notify);
			} else {

			}
		}

	}

	public static void notifyAllUsers(List<User> users, String title,
			String main) {
		for (int i = 0; i < users.size(); i++) {
			new Notification((Long) users.get(i).getEntityId(), title, main)
					.save();
		}
	}

	public static boolean getAllNotifications(long userId) {
		List<Notification> notify = Notification.find("userId=? and status=?",
				userId, false).fetch();
		renderJSON(notify.size());
		return true;
	}

	public static boolean markAllAsRead(long userId) {
		List<Notification> notify = Notification.find("userId=?", userId)
				.fetch();
		for (int i = 0; i < notify.size(); i++) {
			notify.get(i).status = true;
			notify.get(i).save();
		}
		return true;
	}
}
